package com.charging.business.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.charging.business.config.MinFeeManager;
import com.charging.business.utils.DateEx;
import com.charging.business.utils.VehicleClassUtil;
import com.charging.business.vo.FeeEnCalcRequest;
import com.charging.business.vo.FeeEnCalcResponse;
import com.charging.business.domain.FeeEntryInfoModel;
import com.charging.business.enums.Free;
import com.charging.business.exception.CustomizeException;
import com.charging.business.gantry.EntryFeeCalcResponse;
import com.charging.business.gantry.GantryCalcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 入口计费MTC计算方法
 *
 * @author JerryLu
 * @date 2024/9/24 17:01
 * @return
 */
@Component
public class FeeInMtcHandle {

    private static final Logger logger = LoggerFactory.getLogger(FeeInMtcHandle.class);

    private final Free free; //免费信息
    /**
     * 入口车型
     */
    public int enVehicleType = 0;
    /**
     * 入口轴数
     */
    public int enAxleCount = 0;
    /**
     * 入口计费车型
     */
//    public int enFeeVehicleType = 0;
//    /**
//     * 入口计费轴数
//     */
//    public int enFeeAxleCount = 0;
    /**
     * 入口车种
     */
    public int enVehicleClass = 0;
    /**
     * 特殊车辆标识<p>
     * Ox00 -本次通行用于ETC大件运输
     * Ox01 -非优惠车辆
     * Ox02 -绿通车辆
     * Ox03 -联合收割机车辆
     * Ox04 -集装箱车辆
     * Ox05-0xFE -保留 注：可选填
     * 默认写入 OxFF
     */
    public int enVehicleSign = 255;
    /**
     * 入口车牌(含颜色)
     */
    public String enVehicleId = "";
    /**
     * 用户卡发行方
     */
    public String issuerId = "";
    /**
     * 入口时间
     */
    public DateEx enTime = DateEx.make(0);
    @Autowired
    private MinFeeManager minFeeManager;
    @Autowired
    private GantryCalcUtils gantryCalcUtils;

    @Autowired
    public FeeInMtcHandle(Free free) {
        this.free = free;
    }

    /**
     * MTC/CPC计费
     *
     * @param content
     * @param response
     * @return void
     * @author JerryLu
     * @date 2024/8/26 18:45
     */
    public FeeEnCalcResponse run(FeeEnCalcRequest content, FeeEnCalcResponse response) throws CustomizeException {
        if (content.getEnTollStationHex().length() != 8) {
            throw new CustomizeException("入口站Hex编码错误");
        }
        enTime = DateEx.make(content.getCurPassTime(), "yyyy-MM-dd'T'HH:mm:ss");
        enVehicleId = content.getVehicleId().toUpperCase().replaceAll("\\.", ""); //入口车牌处理
        enVehicleType = content.getEnVehicleType();//入口车型
        enAxleCount = content.getEnAxleCount();//入口轴数
        enVehicleClass = content.getVehicleClass(); //入口车种
        enVehicleSign = content.getVehicleSign(); //车辆特殊标识
        if (enVehicleType < 10) {
            enVehicleSign = 255;
        }
        issuerId = content.getIssuerId();

        // 按入口车种设置免费标识，部里应急保障车检查
        checkVehicleFee();

        // 确定入口收费车型
//        checkEnExVType();

        // 兜底费率版本检查
        checkMinFee();

        // 按入口信息(标签信息)计费
        response = this.libraryFee(content, response);
        return response;
    }

    public void checkVehicleFee() {
        //军车及应急救援
        if (enVehicleClass == VehicleClassUtil.AP && VehicleClassUtil.isArmyETC(issuerId)) {// 军车
            free.set(Free.ARMY);
        } else if (enVehicleClass == VehicleClassUtil.ETC_EMER) {// 应急救援
            free.set(Free.ERES);
        } else if (enVehicleId.contains("警") && enVehicleId.contains("晋")) {// 本省警车,注意：为入口车牌
            free.set(Free.POLIC);
        } else if (enVehicleClass == VehicleClassUtil.MTC_JJC) {// 紧急车
            free.set(Free.JJ);
        } else if (enVehicleClass == VehicleClassUtil.MTC_RESCUE) {// 抢险救灾
            free.set(Free.QXJZ);
        }
    }

//    public void checkEnExVType() {
//        int enFeeAxleCount; // enAxleCount = 入口车辆轴数
//        int enFeeVehicleType = 0; // enVehicleType = 入口车型
//        if (enVehicleType > 10) {// 入口为货车
//            if (VehicleClassUtil.isTrailer(enVehicleClass) || enVehicleSign == 0x00) {// 为J1、J2、甩挂车、大件运输车货车
//                int multi = enVehicleType / 10;
//                if (enAxleCount == 3) {
//                    enFeeVehicleType = multi * 10 + 3;
//                } else if (enAxleCount == 4) {
//                    enFeeVehicleType = multi * 10 + 4;
//                } else if (enAxleCount == 5) {
//                    enFeeVehicleType = multi * 10 + 5;
//                } else if (enAxleCount >= 6) {
//                    enFeeVehicleType = multi * 10 + 6;
//                }
//
//                // ETC才有的情况
//                if (enFeeVehicleType < enVehicleType) {
//                    enFeeVehicleType = enVehicleType;
//                }
//            } else {
//                if (enVehicleType == 11 || enVehicleType == 21) {
//                    enFeeAxleCount = 2;
//                } else if (enVehicleType == 12 || enVehicleType == 22) {
//                    enFeeAxleCount = 2;
//                } else if (enVehicleType == 13 || enVehicleType == 23) {
//                    enFeeAxleCount = 3;
//                } else if (enVehicleType ProvinceType.SHAN_XI.getCode() || enVehicleType == 24) {
//                    enFeeAxleCount = 4;
//                } else if (enVehicleType == 15 || enVehicleType == 25) {
//                    enFeeAxleCount = 5;
//                } else if (enVehicleType == 16 || enVehicleType == 26) {
//                    enFeeAxleCount = 6;
//                }
//            }
//        } else {
//            enFeeAxleCount = 2;
//        }
//    }

    public void checkMinFee() throws CustomizeException {
        // 获取最小费额版本号
        String minVersion = minFeeManager.getMinFeeVersion();
        if (minVersion.isEmpty()) {
            throw new CustomizeException("获取兜底费率版本失败");
        }
    }

    /**
     * 动态库计费
     * @param content
     * @param response
     * @return
     * @throws CustomizeException
     */
    public FeeEnCalcResponse libraryFee(FeeEnCalcRequest content, FeeEnCalcResponse response) throws CustomizeException {
        FeeEntryInfoModel mtcDto = JSONObject.parseObject(JSON.toJSONString(content), FeeEntryInfoModel.class);
        mtcDto.setLaneStatus(content.laneType);
        mtcDto.setEnPassTime(content.curPassTime);//无入口时间，使用当前收费门架经过时间当入口时间
        mtcDto.setLastGantryHex("000000");
        mtcDto.setLastPassTime(LocalDateTime.parse(content.curPassTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
        mtcDto.setLastGantryFee(0);
        mtcDto.setLastFeeMileage(0);
        mtcDto.setIssuerId(content.issuerId);
        mtcDto.setCardNetwork(content.CPUNetID);
        mtcDto.setAxleCount(content.enAxleCount);
        mtcDto.setTagType(2);
        mtcDto.setCardType(content.CPUCardType);
        mtcDto.setCardVer(content.CPUVersion);
        mtcDto.setObuSn(content.OBUSN);
        mtcDto.setCpuCardId(content.CPUCardId);
        mtcDto.setPlateHex(content.vehicleId.split("_")[0]);
        mtcDto.setPlateColor(Integer.valueOf(content.vehicleId.split("_")[1]));
        mtcDto.setVehicleType(content.enVehicleType);
        mtcDto.setVehicleWeightLimits(content.obuPermittedTowWeight);
        mtcDto.setVehicleStatusFlag(content.vehicleSign);
        mtcDto.setFeeProvBeginHex("");
        mtcDto.setFeeProvMileage(-1);
        mtcDto.setFeeProvGantryNum(-1);
        mtcDto.setPayFeeSumLocal(-1);
        mtcDto.setRealFeeSumLocal(-1);
        mtcDto.setGantryPassNum(0);
        mtcDto.setGantryPassHex("");
        EntryFeeCalcResponse feeCalcResponse = gantryCalcUtils.libraryFee(mtcDto);
        response = JSONObject.parseObject(JSON.toJSONString(feeCalcResponse), FeeEnCalcResponse.class);
        if (feeCalcResponse.getCode() != 0) {
            response.setCodeInfo(feeCalcResponse.getMsg());
        }

        return response;
    }
}
